﻿package com.kingtone.rongji;

import java.util.ArrayList;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.kingtone.rongji.R;
import com.kingtone.rongji.adapter.RegionAdapter;
import com.kingtone.rongji.biz.Address;
import com.kingtone.rongji.biz.Region;
import com.kingtone.rongji.db.RegionDao;
import com.kingtone.rongji.tool.AppContasts;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.tool.SharedPreferencesUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;

public class AddAddressActivity extends BaseActivity {

	private TextView title = null;
	private ImageView backBtn = null;
	private Spinner province_spinner;
	private Spinner city_spinner;
	private Spinner county_spinner;
	private int pParentId, cParentId;
	private ImageView leftIcon = null;
	private int countyRegionId;
	
	private EditText receiveTo = null; //收货人
	private EditText receivePhone = null;//收货人手机号
	private EditText receiveAddress = null; //收货人详细地址
	private EditText receiveZip = null; //收货人邮编
	private Button submitBtn = null;//提交按钮
	private int isDefault = 0;
	private Context context = AddAddressActivity.this;
	
	
	ArrayList<Region> provinceList = null;
	ArrayList<Region> cityList = null;
	ArrayList<Region> countyList = null;
	RegionDao dao = null;
	int fromFlag = 0;
	Address fromUpdate = null;
	
	private RegionAdapter province_adapter = null;
	private RegionAdapter city_adapter = null;
	private RegionAdapter county_adapter = null;
	private int shippingId;
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_add_address);
		dao = new RegionDao(context);
		Intent intent = getIntent();
		fromFlag = intent.getIntExtra("flag", 0);
		if(fromFlag == AppContasts.TO_MDOFY_ADDRESS)
		{
			fromUpdate = (Address)intent.getSerializableExtra("address");
		}
		setupView();
		isDefault = intent.getIntExtra("isDefault", 0);
	}
	
	private void setupView()
	{
		title = (TextView)findViewById(R.id.title);
		title.setText(getString(R.string.my_receive_address));
		
		loadSpinner();
		backBtn = (ImageView)findViewById(R.id.back);
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) 
			{
				onBackPressed();
			}
		});
		
		leftIcon = (ImageView)findViewById(R.id.left_icon);
		leftIcon.setBackgroundResource(R.drawable.icon_zhi);
		
		receiveTo = (EditText)findViewById(R.id.receive_to);
		
		receivePhone = (EditText)findViewById(R.id.receive_phone);
		receiveAddress = (EditText)findViewById(R.id.receive_address_detail);
		receiveZip = (EditText)findViewById(R.id.receive_address_zip);
		if(fromUpdate != null)
		{
			receiveTo.setText(fromUpdate.getShipTo());
			receivePhone.setText(fromUpdate.getCellPhone());
			receiveAddress.setText(fromUpdate.getAddress());
			receiveZip.setText(fromUpdate.getZipcode());
			isDefault = fromUpdate.getIsDefault().equals("true")?1:0;
		}
		submitBtn = (Button)findViewById(R.id.receive_address_submit);
		submitBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				createOrUpdateShipingAddress(shippingId, fromFlag);
			}
		});
		
	}
	
	private void loadSpinner()
	{
		province_spinner = (Spinner) findViewById(R.id.spinner_province);
		province_spinner.setPrompt("请选择省份");
		provinceList =  dao.findAllProvince();
		province_adapter = new RegionAdapter(context,provinceList);
		
		//province_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    	province_spinner.setAdapter(province_adapter);
    	if(fromFlag == AppContasts.TO_MDOFY_ADDRESS)
    	{
    		int pRegionId = 0;
    		if(fromUpdate != null)
    		{
    			pRegionId = dao.getProvinceRegionIdByParentId(fromUpdate.getRegionId());
    			shippingId= fromUpdate.getShippingId();
    		}
    		for(int i =0; i < provinceList.size(); i++)
    		{
    			if(provinceList.get(i).getRegionId() == pRegionId)
    			{
    				province_spinner.setSelection(i);
    				break;
    			}
    		}
    	}
    	province_spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
    	{	
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) 
			{					
				pParentId = provinceList.get(arg2).getRegionId();
				city_spinner = (Spinner)  findViewById(R.id.spinner_city);
				if(true)
				{	
					city_spinner = (Spinner)  findViewById(R.id.spinner_city);
					city_spinner.setPrompt("请选择城市");
					cityList =  dao.findCityesByParentId(pParentId);
					city_adapter = new RegionAdapter(context,cityList);
					city_spinner.setAdapter(city_adapter);
					if(fromFlag == AppContasts.TO_MDOFY_ADDRESS)
			    	{
			    		int cRegionId = 0;
			    		if(fromUpdate != null)
			    		{
			    			cRegionId = dao.getCityRegionIdByParentId(fromUpdate.getRegionId());
			    		}
			    		for(int i =0; i < cityList.size(); i++)
			    		{
			    			if(cityList.get(i).getRegionId() == cRegionId)
			    			{
			    				city_spinner.setSelection(i);
			    				break;
			    			}
			    		}
			    	}
					city_spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
					{

						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int arg2, long arg3) {
							cParentId = cityList.get(arg2).getRegionId();
							if(true)
							{
								county_spinner = (Spinner) findViewById(R.id.spinner_district);
								county_spinner.setPrompt("请选择县区");
								countyList =  dao.findCountiesByParentId(cParentId);
								county_adapter = new RegionAdapter(context,countyList);
								county_spinner.setAdapter(county_adapter);
								if(fromFlag == AppContasts.TO_MDOFY_ADDRESS)
						    	{
						    		for(int i =0; i < countyList.size(); i++)
						    		{
						    			if(countyList.get(i).getRegionId() == fromUpdate.getRegionId())
						    			{
						    				county_spinner.setSelection(i);
						    				break;
						    			}
						    		}
						    	}
								county_spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
								{

									@Override
									public void onItemSelected(
											AdapterView<?> arg0, View arg1,
											int arg2, long arg3) {
										countyRegionId = countyList.get(arg2).getRegionId();
									}

									@Override
									public void onNothingSelected(
											AdapterView<?> arg0) {
										
										
									}
									
								});
							}
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
							// TODO Auto-generated method stub
							
						}

					});							
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				
			}
		});	
	}
	/**
	 * 新增收货地址
	 */
	private void createOrUpdateShipingAddress(int shippingId, int type)
	{
		String userId = SharedPreferencesUtil.getInstance(context).getString(AppContasts.USERID_KEY);
		String shipTo = receiveTo.getText().toString();
		String cellPhone = receivePhone.getText().toString();
		String address = receiveAddress.getText().toString();
		String zipCode = receiveZip.getText().toString();
		RongJiRestClient.createOrUpdateShipingAddress(userId, shipTo, cellPhone, countyRegionId,address, zipCode, shippingId, type, isDefault, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
				RongJiUtils.showEmptyProgress(context);
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				String result = new String(arg2);
				Log.d("createShipingAddress failure ", result);
				RongJiUtils.dismissProgress();
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				RongJiUtils.dismissProgress();
				
				if(arg2 != null && !new String(arg2).equalsIgnoreCase("null"))
				{
					String result = new String(arg2);
					JSONTokener jsonParser = new JSONTokener(result);  
				    try {
						JSONObject address = (JSONObject) jsonParser.nextValue();
						boolean errorCode = address.optBoolean("Status");
						if(errorCode)
						{
							if(fromFlag == AppContasts.TO_MDOFY_ADDRESS || fromFlag == AppContasts.TO_ADD_ADDRESS) {
								setResult(RESULT_OK, new Intent());
								finish();
							} else {
								Intent intent = new Intent(AddAddressActivity.this, ReceiveAddressActivity.class);
								intent.putExtra("pageFlag", 1);
								startActivity(intent);
							}
						}else
						{
							String errorMsg = address.optString("ErrorMessage");
							if(!TextUtils.isEmpty(errorMsg))
							{
								Toast.makeText(context, errorMsg, Toast.LENGTH_SHORT).show();
							}
						}
						
				    } catch (JSONException e) {
						e.printStackTrace();
					} 
                    
				}
			}	
		});
	}
}
